package com.durian.common.async;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @Author zhouzhiyi
 * @Date 2022/6/30 16:36
 * @Description 异步微信推送
 */
@Service
public class AsyncPushService {


    @Async
    public void asyncPush(final String templateId) {

        //1，配置
        WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
        wxStorage.setAppId("wx47d3d3942ec67b86");
        wxStorage.setSecret("e15c5cb4580507edb0b64f46e6ef673f");
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxStorage);

        try {

            //获取所有关注测试号的用户openId
            List<String> wechatAllUser = wechatAllUser = getWechatAllUser();
            //实现了多人推送
            wechatAllUser.forEach(openId->{
                //2,推送消息
                WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                        .toUser(openId)//要推送的用户openid
                        .templateId(templateId)//模版id
                        .url("http://192.168.0.103/finance/product")//点击模版消息要访问的网址
                        .build();

                try {
                    wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
                } catch (Exception e) {
                    System.out.println("推送失败：" + e.getMessage());
                    e.printStackTrace();
                }
            });
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取所有的用户
     * @param
     * @return
     */
    public List<String> getWechatAllUser() throws InterruptedException {

        String tokenObject = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx47d3d3942ec67b86&secret=e15c5cb4580507edb0b64f46e6ef673f");
        JSONObject jsonObject = JSON.parseObject(tokenObject);
        String access_token =(String) jsonObject.get("access_token");

        System.out.println("=========获取所有用户的openid====token=========="+access_token);
        String AllUser =  HttpUtil.get("https://api.weixin.qq.com/cgi-bin/user/get?access_token="+access_token ) ;
        Map<String, Object> getUser_result = JSON.parseObject(AllUser);
        Map<String, Object> result = (Map<String, Object>) getUser_result.get("data");
        List<String> userList = null;
        if(!"".equals(result.get("count"))){
            userList =  (List<String>) result.get("openid");
        }

        return userList;
    }
}
